﻿
CREATE PROCEDURE [dbo].[InitConturiCoresp]
AS
	SET NOCOUNT ON 
	DECLARE @CodUnitate smallint
	SET @CodUnitate=0
	SELECT @CodUnitate=CAST(Valoare AS smallint) FROM [SetariLocale] WHERE [CodSetare]='UCRT' AND [xUser]=suser_sname() AND [xHost]=host_name()
	
	--PRINT(@CodUnitate) 
	DECLARE @ContEc TipCont
	SELECT @ContEc = Cont FROM ConturiSpeciale WHERE (Tipuri = '{REX}') AND [CodUnitate]=@CodUnitate
	--PRINT(@ContEc)
	--daca nu este definit contul rezultat se adauga unul implicit
	IF @ContEc is null
	BEGIN
		--GOTO ErrorContCoresp
		INSERT INTO [ConturiSpeciale]([Cont],[CodUnitate],[Tipuri],[Descriere])
		SELECT MIN([Cont]),MIN([CodUnitate]),'{REX}','Rezultat patrimonial' FROM Conturi WHERE Denumire like '%rezult%' AND CodUnitate = @CodUnitate

	END	
	DECLARE @ContRez TipCont 

	SELECT TOP 1 @ContRez = Cont FROM [Conturi] WHERE Cont LIKE @ContEc + '%' AND Terminal=1 AND [CodUnitate] = @CodUnitate

	INSERT INTO [ConturiCoresp] ([ContCredit],[ContDebit],[IdJurnal],[Tip],[CodUnitate])
	SELECT Cont AS [ContCredit], 
	(@ContRez) AS [Contdebit],
	[IDJurnal],
	'IC' AS [Tip],
	@CodUnitate
	FROM  [Conturi] a JOIN  (SELECT DISTINCT [IDJurnal] FROM [RulajeDoc] WHERE [CodUnitate]=@CodUnitate) b ON dbo.GetContClass(a.Cont) = '6' AND a.Terminal = 1   AND
	NOT EXISTS( SELECT [IDjurnal],[ContCredit] FROM [ConturiCoresp] x where  [ContCredit]=a.cont 
	and [IDJurnal] = b.[IdJurnal] AND x.[CodUnitate]=@CodUnitate) AND [CodUnitate]=@CodUnitate    
	
	INSERT INTO [ConturiCoresp] ([ContDebit],[ContCredit],[IdJurnal],[Tip],[CodUnitate])
	SELECT Cont AS [ContDebit], 
	(@ContRez) AS [ContCredit],
	[IDJurnal],
	'IC' AS [Tip],
	@CodUnitate
	FROM  [Conturi] a JOIN  (SELECT DISTINCT [IDJurnal] FROM [RulajeDoc] WHERE [CodUnitate]=@CodUnitate) b ON dbo.GetContClass(a.Cont) = '7' AND a.Terminal = 1  AND
	NOT EXISTS(SELECT [IDjurnal],[ContDebit] FROM [ConturiCoresp] x where  [ContDebit]=a.cont 
	and [IDJurnal] = b.[IdJurnal] AND x.[CodUnitate]=@CodUnitate) AND [CodUnitate]=@CodUnitate
	
	DELETE FROM [ConturiCoresp] WHERE 
	NOT EXISTS(
	SELECT [Cont] FROM [Conturi] WHERE Terminal = 1 and [Cont]=[ConturiCoresp].ContDebit and [CodUnitate]=@CodUnitate)
	OR
	NOT EXISTS(
	SELECT [Cont] FROM [Conturi] WHERE Terminal = 1 and [Cont]=[ConturiCoresp].ContCredit  and [CodUnitate]=@CodUnitate)
	
	GOTO Gata
	Error:
	ErrorContCoresp:
		RAISERROR ('Nu a fost definit nici un cont rezultat!',16,-1)
	Gata:
	RETURN